<template>
    <div class="chat" ref="chatContent">
        <v-navbar></v-navbar>
        <div class="chat-wrapper">
            <ul>
                <li v-for="(v, i) in nwes" :key="i" class="item">
                    <div v-if="show(i)" class="time">{{v.createTime | formatDate }}</div>
                    <div class="wrapper" :class="{'right': v.ii === 0}">
                        <img class="img" :src="user" width="40" height="40" alt="">
                        <div class="jiao"></div>
                        <p class="text">{{v.msg}}</p>
                    </div>
                </li>
            </ul>
        </div>
        <div class="input">
            <input type="text" v-model="content" ref="input">
            <button class="send" @click="doSend">发送</button>
        </div>
    </div>
</template>

<script>
import navbar from '@c/navbar/navbar'
import user from '@imgs/chat/user.png'
import { mapState, mapMutations } from 'vuex'
import { formatDate } from '@js/formatDate.js'
import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'
import { Connect } from '@api/apiUrl'
// const time1 = new Date

export default {
	name: 'chat',
	data() {
		return {
			user: user,
			content: '',
			// 模拟数据
			nwes: [
				// {
				// 	userId: 1,
				// 	content:
				// 		'这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息这是一跳消息',
				// 	ctime: new Date('2017/09/15 18:00:00').getTime(),
				// },
				// {
				// 	userId: 1,
				// 	content: '这是一跳消息这',
				// 	ctime: new Date('2017/09/15 18:00:40').getTime(),
				// },
				// {
				// 	userId: 0,
				// 	content: '这是消息',
				// 	ctime: new Date('2017/09/15 18:35:40').getTime(),
				// },
			],
			sock: {},
			stomp: null,
			selfIcon: '',
		}
	},
	components: {
		'v-navbar': navbar,
	},
	computed: {
		...mapState(['wtitle', 'rback']),
	},
	methods: {
		...mapMutations(['WTITLE', 'RBACK']),
		// 获取聊天记录
		e_getChatHis() {
			let getData = {
				userId: localStorage.getItem('userId'),
			}
			tokenPost(tokenLink.chat.getCharHis, getData).then(re => {
				if (re.status == 0) {
					let chatHis = re.data
					for (let i = 0; i < chatHis.length; i++) {
						if (chatHis[i].isKf == 0) {
							chatHis[i].ii = 0
							this.user = this.selfIcon
						} else {
							chatHis[i].ii = 1
						}
					}
					this.nwes = chatHis
				}
			})
		},
		socket() {
			this.sock = new SockJS(
				`${
					Connect.baseURL
				}webSocketServer/?token=${localStorage.getItem(
					'userId',
				)}&type=1`,
			)
			this.stomp = Stomp.over(this.sock)
			let _this = this
			this.stomp.connect(
				{},
				function(frame) {
					//连接成功后订阅消息接口
					//订阅个人消息
					_this.stomp.subscribe('/user/queue/chat', function(
						response,
					) {
						var result = JSON.parse(response.body)
						let hisobj = {}
						hisobj.ii = 1
						hisobj.msg = result.msg
						hisobj.createTime = result.createTime
						_this.nwes.push(hisobj)
						// console.log(result)
					})
					//消息发送结果
					_this.stomp.subscribe('/user/queue/msg/result', function(
						response,
					) {})
				},
			)
		},
		// 发送消息
		doSend() {
			if (this.content === '') {
				return
			}
			this._showView()
		},
		// 数据添加到数组中
		_showView() {
			let date = {
				ii: 0,
				msg: this.content,
				createTime: new Date().getTime(),
			}
			this.nwes.push(date)

			// 发送消息
			this.stomp.send('/ws/chatKf', {}, this.content)

			this.content = ''
		},
		// 判断时间是否在前台显示
		show(index) {
			if (index === 0) {
				return true
			}
			if (this.nwes[index].ctime - this.nwes[index - 1].ctime > 60000) {
				return true
			} else {
				return false
			}
		},
		// 消息推送滚动条滑动到底部
		_scrollBottom() {
			this.$nextTick(() => {
				this.$refs.input.focus()
				let scroll = this.$refs.chatContent
				scroll.scrollTop = scroll.scrollHeight
			})
		},
	},
	created() {
		this.socket()
		this._scrollBottom()
		this.WTITLE('联系客服')
		this.RBACK(true)

		this.e_getChatHis()

		// 设置个人头像
		if (this.$store.state.selfIcon) {
			this.selfIcon = this.$store.state.selfIcon
		}
	},
	watch: {
		nwes() {
			this._scrollBottom()
			return this.nwes
		},
	},
	filters: {
		formatDate(time) {
			let date = new Date(time)
			return formatDate(date, 'yyyy/MM/dd hh:mm:ss')
		},
	},
}
</script>